import path from 'path';

class Scene {
  /** @type number 格式 int */
  id = -1;
  /** @type string */
  series = null;
  /** @type string */
  name = null;
  /** @type string monitor-js */
  jsEntry = null;
  /** @type string monitor-html */
  htmlTemplate = null;

  /**
   * @returns {Scene}
   */
  clone = function () {
    return cloneOne.call(this, this); // 第一个 this 无效, 第二个 this = cloneOne 参数 raw
  };

  /**
   * @returns {string}
   */
  completeName = function () {
    if (this.scene || this.series) {
      return `${this.series}/${this.scene}`;
    }
    return null;
  };

  jsPath = function () {
    return path.resolve('/aurora-res', this.series, this.jsEntry);
  };

  htmlPath = function () {
    return path.resolve('/aurora-res', this.series, this.htmlTemplate);
  };
}

// 暂存数据
/** @type {Scene[]} */
let scenes = [];

/**
 * @param {object} raw
 * @returns {Scene}
 */
function cloneOne(raw) {
  let s = new Scene(); // Object.assign(s, raw)
  s.id = raw.id;
  s.series = raw.series;
  s.name = raw.name;
  s.jsEntry = raw.jsEntry;
  s.htmlTemplate = raw.htmlTemplate;
  return s;
}

/**
 * 刷新全部数据
 * @param {any[]} array 
 */
function refreshAll(array) {
  scenes = array.map(item => cloneOne(item));
}

/**
 * @param {string} seriesName 
 * @param {string} sceneName 
 * @returns {Scene}
 */
function getOne(seriesName, sceneName) {
  let array = scenes.filter(item => item.series == seriesName && item.name == sceneName);
  if (array.length) {
    return array[0].clone();
  } else {
    return null;
  }
}

// 后续, 获取 html 代码:
// fetch(getOne('timer', 'timer').htmlPath()).then(res => res.text()).then(s => console.log(s))

export default {Scene, cloneOne, refreshAll, getOne};
